package com.dayu.springbootcache.service;

import com.dayu.springbootcache.entity.Department;
import com.dayu.springbootcache.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.stereotype.Service;
@CacheConfig(cacheNames = "dept",cacheManager = "deptCacheManager")
@Service
public class DepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;
    @Qualifier("deptCacheManager")
    @Autowired
    RedisCacheManager deptCacheManager;

//    /**
//     * 缓存的数据能存入json
//     * 第二次从缓存中查询就不能反序列化
//     * @param id
//     * @return
//     */
//    @Cacheable(cacheManager = "deptCacheManager")
//    public Department getDeptById(Integer id){
//        System.out.println("查询部门"+id);
//        Department department=departmentMapper.getDeptById(id);
//        //获取某个缓存
//        Cache dept = deptCacheManager.getCache("dept");
//        dept.put("dept:1",department);
//        return department;
//    }

    /**
     * 通过代码获取缓存添加缓存
     * 缓存的数据能存入json
     * 第二次从缓存中查询就不能反序列化
     * @param id
     * @return
     * 注意这里就没有注解了
     */
    public Department getDeptById(Integer id){
        System.out.println("查询部门"+id);
        Department department=departmentMapper.getDeptById(id);
        //获取某个缓存
        Cache dept = deptCacheManager.getCache("dept");
        dept.put("dept:1",department);//放了一条数据
        return department;
    }
}
